/* Copyright (c) 2004-2023 Peigen.info. All rights reserved. */

package info.peigen.hotpot.manage.core.service.processor.auth.check;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.manage.core.cache.ManageCache;
import info.peigen.hotpot.manage.core.service.order.LoginOrder;
import info.peigen.hotpot.manage.core.service.processor.AbstractHotpotManageServiceProcessor;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;

/**
 * <b>(AuthCheckValidCodeProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/8/30
 */
@Slf4j
@Component
public class AuthCheckValidCodeProcessor extends AbstractHotpotManageServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 21;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        String validCode      = getValidCode(serviceContext);
        String validCodeReqNo = getValidCodeReqNo(serviceContext);
        String cacheValidCode = (String) cache.get(ManageCache.AUTH_VALID_CODE_CACHE_KEY + validCodeReqNo);
        Assert.isTrue(StrUtil.equalsAnyIgnoreCase(validCode, cacheValidCode), () -> new BusinessException(ResultCode.FAILURE, "验证码有误[validCode=" + validCode + "," +
                "validCodeReqNo=" + validCodeReqNo + ",cacheValidCode=" + cacheValidCode + "]"));
    }

    private String getValidCode(ProcessorServiceContext context) {
        if (context.getOrder() instanceof LoginOrder order) {
            return order.getValidCode();
        }
        return null;
    }

    private String getValidCodeReqNo(ProcessorServiceContext context) {
        if (context.getOrder() instanceof LoginOrder order) {
            return order.getValidCodeReqNo();
        }
        return null;
    }
}
